﻿using System.Linq;
using InvestmentIntelligence.TradingData.Adapters.Mus.Models;
using InvestmentIntelligence.TradingData.DataProcessing.DataResolvers;
using System.Collections.Generic;

namespace InvestmentIntelligence.TradingData.Adapters.Mus.MarketIndicators.TimeLineBuilders
{
    public class ExponentialMovingAverageTimelineBuilder : ITimelineBuilder
    {
        private readonly int _window;

        public ExponentialMovingAverageTimelineBuilder(int window)
        {
            _window = window;
        }
        
        public List<Timeline> Build(List<TimeSerieInfo> timeSeries)
        {
            var result = new List<Timeline>();
            if (timeSeries.Count < _window) return result;

            var queue = new Queue<TimeSerieInfo>();
            var sum = 0m;
            var multiplier = 2m / (_window + 1);
            for (var i = 0; i < timeSeries.Count; i++)
            {
                var timeSerie = timeSeries[i];

                if (i < _window)
                {
                    sum += timeSerie.ClosePrice;
                    queue.Enqueue(timeSeries[i]);
                }

                if (i == _window - 1)
                {
                    //Same as SMA on day equal to _window
                    result.Add(new Timeline
                    {
                        Date = timeSerie.Date,
                        Value = sum / _window,
                    });
                }
                else if (i > _window - 1)
                {
                    var lastEma = result.Last().Value;
                    var ema = (timeSerie.ClosePrice - lastEma) * multiplier + lastEma;
                    result.Add(new Timeline
                    {
                        Date = timeSerie.Date,
                        Value = ema,
                    });
                }
            }

            return result;
        }
    }
}
